package com.sample.springbatch.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zwg on 2017/9/7.
 */
@Configuration
@ConfigurationProperties(prefix = "serverInfoConfig")
public class ServerInfoProperties {

    Logger logger = LoggerFactory.getLogger(ServerInfoProperties.class);


    /**
     * yml 配置文件中增加如下配置
     * serverInfo:
     *   serNoToHostMap:   #目前只支持0-9，否则服务器无法启动
     *     10-108-48-64: 1  #IP地址配置，“.”使用中划线替换
     *     zwg-PC: 11   #host name配置
     */
    private Map<String,Integer> serNoToHostMap = new HashMap<>();
    //当前服务器编号
    private int currentServerNumber = 0;

    
    @PostConstruct
    public void init(){

        String hostAddress = "";
        String hostName = "";
        try{
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            hostName = InetAddress.getLocalHost().getHostName();

            //logger.info("current server host name and address is :{},{}",hostName,hostAddress);
            if(!StringUtils.isEmpty(hostAddress)){
                hostAddress = hostAddress.replaceAll("\\.","-");
            }
            logger.info("current server host name and address is :{},{}. server config:{}",hostName,hostAddress,serNoToHostMap.toString());
            if(serNoToHostMap.containsKey(hostName)){
                this.currentServerNumber = serNoToHostMap.get(hostName);
            }else if(serNoToHostMap.containsKey(hostAddress)){
                this.currentServerNumber = serNoToHostMap.get(hostAddress);
            }else{
                logger.error("current server host name:{} or address:{} not in config:{}",hostName,hostAddress,serNoToHostMap.toString());
                //throw new RuntimeException("ServerInfoProperties init error");
            }
            if(this.currentServerNumber>10 || this.currentServerNumber<0){
                logger.error("server number must be 0-9 current number:{}",this.currentServerNumber);
                //throw new RuntimeException("ServerInfoProperties init error");
            }

        }catch (UnknownHostException e){
            logger.error("server not get host name and address.",e);
            //throw new RuntimeException(e);
        }

        logger.info("current server number is :{}",this.currentServerNumber);
    }

    public Map<String, Integer> getSerNoToHostMap() {
        return serNoToHostMap;
    }

    public void setSerNoToHostMap(Map<String, Integer> serNoToHostMap) {
        this.serNoToHostMap = serNoToHostMap;
    }

    public int getCurrentServerNumber() {
        return currentServerNumber;
    }
}
